package cn.net.autocode.platform.table;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import cn.net.autocode.dbManager.Dao;
import cn.net.autocode.dbManager.IdWorker;
import cn.net.autocode.core.bean.ResultT;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/platform/tableRef")
@RestController("platformTableRef")
public class TableRef {

    private final Dao dictDao;

    public TableRef(@Qualifier("dictDao") Dao dictDao) {
        this.dictDao = dictDao;
    }

    @RequestMapping("load")
    public ResultT load(@RequestBody JSONObject param){
        JSONArray array = dictDao.queryJSONArray("select * from ac_table_ref where table_id=? order by fk_table,fk_field",param.getString("tableId"));
        return ResultT.success(array);
    }


    @RequestMapping("/save")
    public ResultT save(@RequestBody JSONObject param){
        param.put("id", IdWorker.ulid());
        dictDao.createJSON(param,"ac_table_ref");
        dictDao.executeUpdate("update ac_table set is_sync='N' where id=?",param.getString("tableId"));
        return ResultT.success(param);
    }

    @RequestMapping("/change")
    public ResultT change(@RequestBody JSONObject param){
        dictDao.updateJSON(param, "ac_table_ref");
        return ResultT.success();
    }

    @RequestMapping("/delete")
    public ResultT delete(@RequestBody JSONObject param){
        dictDao.executeUpdate("update ac_table set is_sync='N' where id in (select table_id from ac_table_ref where id=?)",param.getString("id"));
        dictDao.executeUpdate("delete from ac_table_ref where id=?",param.getString("id"));
        return ResultT.success();
    }
}
